import ChatServiceClass from "../services/chatService.mjs";
import {ChatEventType, COZE_CN_BASE_URL, CozeAPI, RoleType} from "@coze/api";
import OpenAI from "openai";

export const chatStream=async (req, res)=> {
    //解析GET请求参数
    const type = req.query.type;
    const content=req.query.content;
    const contentType=req.query.contentType;
    const info={
        content,
        contentType
    }
    const token=req.headers['authorization'];
    // console.log(token)
    // 设置流式响应头
    res.setHeader('Content-Type', 'text/event-stream');
    res.setHeader('Cache-Control', 'no-cache');
    res.setHeader('Connection', 'keep-alive');

    let isConnectionAlive = true;

    // // 监听客户端断开连接
    // req.on('close', () => {
    //     isConnectionAlive = false;
    //     console.log('Client disconnected');
    // });

    // 心跳包：每 25 秒发送一次空行
    // const heartbeatInterval = setInterval(() => {
    //     if (isConnectionAlive) {
    //         res.write(': heartbeat\n\n'); // SSE 规范中心跳格式
    //     }
    // }, 25000);

    try{
        const chatIns = new ChatServiceClass(type,token);
        console.log(chatIns)
        //!!!await底层函数为异步，必须这个也要等，否则返回结果为Promise<pending>!!!
        const result = await chatIns.chatStream(info);
        const stream=result.data.res;
        console.log(stream)
        for await (const part of stream) {
            console.log(part)
            if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
                const content = part.data.content
                console.log(content);
                process.stdout.write(content);
                res.write(content)
            }
            if (part.event === ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
                console.log("结束了")
            }
        }
    }catch (err){
        res.write(`event: error\n${JSON.stringify({ message: err.message })}\n\n`);
    }finally {
        // clearInterval(heartbeatInterval); // 清除心跳定时器
        res.end(); // 确保连接关闭
    }
}




export const chatCoze=async (req, res) => {
    try {
        //解析GET请求参数
        const content = req.query.content;
        const contentType = req.query.contentType;
        const info = {
            content,
            contentType
        }
        // const token = req.headers['authorization'];
        // 设置流式响应头
        res.setHeader('Content-Type', 'text/event-stream');
        // res.setHeader('Cache-Control', 'no-cache');
        res.setHeader('Connection', 'keep-alive');
        res.setHeader('Transfer-Encoding', 'chunked');

        let isConnectionAlive = true;

        // // 心跳机制（每25秒发送）
        // const heartbeat = setInterval(() => {
        //     res.write(': heartbeat\n\n');
        // }, 25000);


        // 监听关闭事件时清除定时器
        req.on('close', () => {
            // clearInterval(heartbeat);
            // isConnectionAlive=false;
            // console.log('Client disconnected');
            // res.write(`event: close\ndata: \n\n`); // 完整结束标记
            console.log("close")
            res.end();
        });

        if(isConnectionAlive){
            const botId = process.env.COZE_BOT_ID;
            const baseURL = COZE_CN_BASE_URL;
            const token=process.env.COZE_API_Token

            const client = new CozeAPI({
                baseURL,
                token,
            });
            const stream = await client.chat.stream({
                bot_id: botId,
                additional_messages: [
                    {
                        role: RoleType.User,
                        content: info.content,
                        content_type: info.contentType,
                    },
                ],
            });
            let buffer = '';

            for await (const part of stream) {
                if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
                    const content = part.data.content;
                    const encoder = new TextEncoder();
                    //
                    // // 强制使用双换行符作为消息分隔符
                    res.write(encoder.encode(`data: ${content.replace(/\n/g, "\\n")}\n\n`));

                }
                if (part.event === ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
                    //此次解答结束，待优化处理
                    res.write(`event: close\ndata: \n\n`); // 完整结束标记
                    console.log("结束了");
                    isConnectionAlive=false;
                    res.end();  // 显式关闭连接
                    break;
                }
            }
        }
    }
    catch (err){
        // 错误处理（符合 SSE 格式）
        res.write(`event: close\n`);
        res.end()
    }finally {
        if (!res.headersSent) {
            res.status(500).end();
        }
    }
}
export const chatOpenAI=async (req, res) => {
    const openai = new OpenAI({
        apiKey: "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",
        baseURL: "https://api.openai.com/v1" // 可替换为第三方 API 地址
    });

    const stream = await openai.chat.completions.create({
        model: "gpt-3.5-turbo",
        messages: [{ role: "user", content: "解释量子力学" }], // 需维护对话历史数组
        stream: true,
    });
    console.log(stream)
    for await (const chunk of stream) {
        console.log(chunk)
        const content = chunk.choices[0]?.delta?.content || '';
        res.write(`data: ${JSON.stringify({ content })}\n\n`);
    }
}
